<template>
  <div>
    <el-card>
      <el-tree
        :data="allData"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="render"
      ></el-tree>
    </el-card>
    <el-dialog
      title="添加新节点"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <el-input v-model="newPartName"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNode">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  import { uuid } from '@/utils/index'
  export default {
    name: 'ProblemTree',
    props: {
      data: { type: Array, default: () => [] },
      usual_drop: Array,
      end_drop: Array,
      root_drop: Array,
      delete_node: Function,
      rename: Function,
      add_node: Function,
    },
    data() {
      return {
        allData: [],
        currentId: '',
        currenContent: '',
        centerDialogVisible: false,
        newPartName: '',
        node: {
          parentId: '',
          faultName: '',
          faultLevel: 1,
          sort: 1,
          faultId: '',
          faultType: 1,
        },
      }
    },
    watch: {
      data() {
        this.transformData()
      },
    },
    mounted() {
      this.transformData()
    },
    created() {
      console.log(this.data)
      console.log(this.root_drop)
      console.log(this.end_drop)
      console.log(this.usual_drop)
    },

    methods: {
      addNode() {
        let list = _.cloneDeep(this.data)
        this.node.faultName = this.newPartName
        //调用add API
        if (this.add_node) {
          this.add_node(this.node).then(() => {
            list.push(this.node)
            this.$baseEventBus.$emit('reload-router-view')
            this.$message({
              type: 'success',
              message: '添加成功!',
            })
            this.newPartName = ''
            this.centerDialogVisible = false
          })
        }
      },
      cancel() {
        this.currentId = ''
      },
      ok(data) {
        let list = _.cloneDeep(this.data)
        let item = list.find((l) => l.faultId == data.faultId)
        item.faultName = this.currenContent

        if (this.rename) {
          this.rename(item).then(() => {
            this.$emit('update:data', list)
            this.$message({
              type: 'success',
              message: '修改成功!',
            }),
              (this.currentId = '')
          })
        }
      },
      handleInput(v) {
        this.currenContent = v
      },
      //后台删除后，前端数据同步更新
      remove(id) {
        let list = _.cloneDeep(this.data)
        list = list.filter((l) => l.faultId != id)
        this.$emit('update:data', list)
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      },
      handleRemove(data) {
        this.$confirm(`此操作将永久删除 ${data.faultName}, 是否继续?`, '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            //调用删除API
            if (this.delete_node) {
              this.delete_node(data.faultId).then(() => {
                this.remove(data.faultId)
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      handleRename(data) {
        this.currenContent = data.faultName
        this.currentId = data.faultId
      },
      //添加选择项节点
      handleAddCheckPoint(data) {
        this.centerDialogVisible = true
        this.node.parentId = data.faultId
        this.node.faultId = uuid(32)
        this.node.faultLevel = data.faultLevel + 1
        this.node.sort = 1
        this.node.faultType === data.faultType
      },
      handleCommand(data, value) {
        console.log(value)
        if (value === 'addCheckPoint') {
          this.handleAddCheckPoint(data)
        } else if (value === 'rename') {
          this.handleRename(data)
        } else if (value === 'rm') {
          this.handleRemove(data)
        }
      },
      render(h, { node, data, store }) {
        let list = []
        if (data.faultLevel == 0) {
          list = this.root_drop
        } else if (data.faultLevel == 3) {
          list = this.end_drop
        } else {
          list = this.usual_drop
        }
        console.log(list)
        return (
          <div style={{ with: '100%' }}>
            {data.faultLevel === 0 ? (
              <i class="el-icon-c-scale-to-original"></i>
            ) : data.faultLevel === 1 ? (
              <i class="el-icon-document-copy"></i>
            ) : (
              <i class="el-icon-suitcase"></i>
            )}
            {data.faultId === this.currentId ? (
              <el-input
                value={this.currenContent}
                on-input={this.handleInput}
              ></el-input>
            ) : (
              data.faultName
            )}
            {data.faultId !== this.currentId ? (
              <el-dropdown
                placement="bottom-start"
                trigger="click"
                on-command={this.handleCommand.bind(this, data)}
              >
                <span class="el-dropdown-link">
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  {list.map((item) => (
                    <el-dropdown-item command={item.op}>
                      {item.value}
                    </el-dropdown-item>
                  ))}
                </el-dropdown-menu>
              </el-dropdown>
            ) : (
              <span style="float:'right'">
                <el-button type="text" on-click={this.ok.bind(this, data)}>
                  确认
                </el-button>
                <el-button type="text" on-click={this.cancel}>
                  取消
                </el-button>
              </span>
            )}
          </div>
        )
      },
      transformData() {
        console.log(this.data)
        if (!this.data) {
          this.allData = [{ key: 0, label: '根节点', id: '001' }]
          return
        }
        let AllData = _.cloneDeep(this.data)
        // console.log(AllData)
        let treeMapList = AllData.reduce((memo, current) => {
          memo[current['faultId']] = current
          return memo
        }, {})
        let treeData = AllData.reduce((array, current) => {
          let parentId = current.parentId
          let faultLevel = current.faultLevel
          let parent = treeMapList[parentId]
          if (faultLevel == 0) {
            //根元素
            array.push(current)
          } else if (parent) {
            parent.children
              ? parent.children.push(current)
              : (parent.children = [current])
          }
          return array
        }, [])
        this.allData = treeData
        // console.log(treeData)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .el-tree {
    width: 50%;
    .el-dropdown {
      float: right;
    }
    .el-tree-node_content {
      height: 32px;
    }
    .el-input {
      width: 50%;
    }
  }
</style>
